package consumer

import (
	"encoding/json"
	"github.com/streadway/amqp"
	"go.uber.org/zap"
	"niu-video/app/consts"
	"niu-video/app/model"
	"niu-video/app/repository"
	"niu-video/pkg/logger"
	"niu-video/pkg/rabbitmq"
)

func registerLikeConsumer() {
	// 新建连接
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_LIKE_EXCHANGE, consts.RABBITMQ_LIKE_ROUTE, consts.RABBITMQ_LIKE_QUEUE)
	// 执行消费
	rabbit.Consume(func(d amqp.Delivery) (err error) {
		var likeMessage model.LikeMessage
		if err := json.Unmarshal(d.Body, &likeMessage); err != nil {
			logger.Info("rabbitmq", zap.String("like", "json解析失败！"))
		}
		switch likeMessage.ActionType {
		case 1:
			err = repository.LikeRepository.Create(&model.Like{
				VideoID: likeMessage.VideoID,
				UserID:  likeMessage.UserID,
			})
			if err != nil {
				logger.Error("rabbitmq", zap.String("create", err.Error()))
				return err
			}
		case 2:
			err = repository.LikeRepository.Delete(likeMessage.VideoID, likeMessage.UserID)
			if err != nil {
				logger.Error("rabbitmq", zap.String("delete", err.Error()))
				return err
			}
		}
		return err
	})
}
